<?php
namespace Library;
//header("Content-type:text/html;charset=utf-8");

//取通讯录
// $testyun=new TestYun('app');
// $testyun->getcomm();

//取签到
//$testyun=new TestYun('resGroupSecret');
//$testyun->getclock();


function object_array($array) {     
	if(is_object($array)) {
		$array = (array)$array; 
	}if(is_array($array)) {  
      foreach($array as $key=>$value) {  
        $array[$key] = object_array($value);              
	  }      
    }      
    return $array;
}




class TestYun {
	
	public $appid = "";
public $appsecret = "";
public $token = "";
public $eid = "";
public $secret='';

	function __construct($Authtype) {
		$this->appid = "500065546";
		$this->appsecret ="CloudHubJ2eeDemo";
		$this->token='';
		$this->eid='15034412';   //团队EID：15034412
		$this->secret='Kx2oDbUvm1hTlYHNUywIKgk0Ept8txFq';   //系统授权 签到数据
		
		if($Authtype=='resGroupSecret'){
			$token=object_array(json_decode(file_get_contents("resGroupSecret.log")));
		}
		
		if($Authtype=='app'){
			$token=object_array(json_decode(file_get_contents("app.log")));
		}
		
		if($token['expireIn']+7200>time()){
			$this->token=$token['accessToken'];
		}else{
			$temp=$this->getAccessToken($Authtype);
			$this->token=$temp['data']['accessToken'];
		}

	}
	
	function getAuth2(){
		//appAuth2协议生成算法 获取用户身份
		$url="https://open.yunzhijia.com/opentest/webdebug/encryptAuth2";
        $data=(json_encode(array('oauthConsumerKey'=>$this->appid,'consumerSecret'=>$this->appsecret)));
		$res=$this->_post($url,$data);
		$res_arr=object_array(json_decode($res));
		return $res_arr;
	}
	
	
	function getAccessToken($Authtype){
		$Auth2=$this->getAuth2();
		$timestamp=$Auth2['data']['encode_data']['timestamp'];
		
		/*
		 * 获取用户上下文信息	/gateway/ticket/user/acquirecontext/...	app
		 轻应用获取组织与人员信息	/gateway/opendata-control/data/...	app
		 待办消息	/gateway/newtodo/open/...	app
		 报表秀秀	/gateway/linkerp/...	team
		 审批	/gateway/workflow/...	team
		 通讯录同步	/gateway/openimport/open/...	resGroupSecret
		 签到	/gateway/attendance/data/...	resGroupSecret
		 时间助手	/gateway/cloudwork/newwork/...	resGroupSecret
		 生态圈	/gateway/open/linkspace/...	resGroupSecret
		 */
		
		
		//获取access_tokenPost
		$url2="https://www.yunzhijia.com/gateway/oauth2/token/getAccessToken";
		if($Authtype=='app'){
			$data2=(json_encode(array('appId'=>$this->appid,'secret'=>$this->appsecret,'timestamp'=>$timestamp,'scope'=>$Authtype)));
		}
		
		if($Authtype=='resGroupSecret'){
			$data2=(json_encode(array('eid'=>$this->eid,'secret'=>$this->secret,'timestamp'=>$timestamp,'scope'=>$Authtype)));
		}
		
		
		$res2=$this->_post($url2,$data2);
		$res2_arr=object_array(json_decode($res2));
		
		if($res2_arr['errorCode']==0){
			 if($Authtype=='resGroupSecret'){
			 	file_put_contents("resGroupSecret.log", json_encode(array(
			 	'accessToken'=>$res2_arr['data']['accessToken'],
			 	'refreshToken'=>$res2_arr['data']['refreshToken'],
			 	'expireIn'=>time())));
			 }
			 if($Authtype=='app'){
			 	file_put_contents("app.log", json_encode(array(
			 	'accessToken'=>$res2_arr['data']['accessToken'],
			 	'refreshToken'=>$res2_arr['data']['refreshToken'],
			 	'expireIn'=>time())));
			 }
			
		return 	$res2_arr;
		}else{
			print_r($res2_arr);
		}
		
	}
	
	//签到记录
	function getclock($stime,$etime,$openIds){
		$content_type="application/x-www-form-urlencoded";
		$accessToken=$this->token;
		//获取移动签到明细
		$url4="https://www.yunzhijia.com/gateway/attendance-data/v1/clockIn/list?accessToken=$accessToken";
		//$url4="https://www.yunzhijia.com//gateway/attendance-data/v1/clockIn/day/list?accessToken=$accessToken";
		$data4=array('workDateFrom'=>$stime,'workDateTo'=>$etime,'start'=>1,'limit'=>200,'eid'=>$this->eid,'openIds'=>$openIds);
		
		$clock=object_array(json_decode($this->http_post($url4,$data4,$content_type)));
		//print_r($clock);
		return $clock;
	}
	
	//通讯录
	function getcomm(){
		$content_type="application/x-www-form-urlencoded";
		$accessToken=$this->token;
		$url3="https://www.yunzhijia.com/gateway/opendata-control/data/getallpersons?accessToken=$accessToken";
	
		$data3=array('eid'=>$this->eid,'time'=>'2008-08-02 01:40:3');
		
		
		$allpersons=object_array(json_decode($this->http_post($url3,$data3,$content_type)));
		return($allpersons);
	}
	
	
	function _postSingle($mobile, $content) {
		$params = array (
				'account' => $this->account,
				'password' => $this->passwd,
				'mobile' => $mobile,
				'content' => $content,
				'action'=>'send'
		);
		
		$result=$this->http_post($this->url,$params);
// 		echo $this->url; 
// print_r($params);
// print_r($result);
// 		die();
		$res = @simplexml_load_string($result,NULL,LIBXML_NOCDATA);
		$res = json_decode(json_encode($res),true);
		return $res;
      //  return $this->xml_to_array($result);
		//$result = self::$single->PostSingle ( $params );
		//return self::_getCodeStatus($result->PostSingleResult);
	}
	
	function xml_to_array( $xml )
	{
		$reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/";
		if(preg_match_all($reg, $xml, $matches))
		{
			$count = count($matches[0]);
			$arr = array();
			for($i = 0; $i < $count; $i++)
			{
			$key= $matches[1][$i];
			$val = $this->xml_to_array( $matches[2][$i] );  // 递归
			if(array_key_exists($key, $arr))
			{
			if(is_array($arr[$key]))
			{
			if(!array_key_exists(0,$arr[$key]))
			{
			$arr[$key] = array($arr[$key]);
			}
			}else{
				$arr[$key] = array($arr[$key]);
			}
			$arr[$key][] = $val;
				}else{
					$arr[$key] = $val;
				}
				}
				return $arr;
				}else{
				return $xml;
			}
	}
	
	//传json串
 function _post($url, $data,$content_type='') {

 	if(!$content_type){
 		$content_type='application/json;charset=UTF-8';
 	}
    $headers = array(
        "content-type: $content_type",//设置请求头  请求的内容格式，编码
        "Accept: application/json",   //Accept字段头确定客户端可以接收的媒体类型
        "Cache-Control: no-cache",
        "Pragma: no-cache",
    );
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60); //设置超时
    if(0 === strpos(strtolower($url), 'https')) {
        //https请求
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //从证书中检查SSL加密算法是否存在
    }
    curl_setopt( $ch, CURLOPT_POST, true);
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
    $resp = curl_exec ( $ch );
    curl_close ( $ch );
    return $resp;
}



//传数组
	function http_post($url, $post_array = array(),$content_type='', $ctime = 3, $timeout = 4)
	{
		
	
		if (!is_array($post_array))
			return FALSE;
	
		$post_data = '';
		foreach ($post_array as $key => $var)
		{
			$post_data .= $key . '=' . urlencode($var) . '&';
		}
		$data = substr($post_data, 0, -1);
	
	if(!$content_type){
 		$content_type='application/json;charset=UTF-8';
 	}
    $headers = array(
        "content-type: $content_type",//设置请求头  请求的内容格式，编码
        "Accept: application/json",   //Accept字段头确定客户端可以接收的媒体类型
        "Cache-Control: no-cache",
        "Pragma: no-cache",
    );
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60); //设置超时
    if(0 === strpos(strtolower($url), 'https')) {
        //https请求
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //从证书中检查SSL加密算法是否存在
    }
    curl_setopt( $ch, CURLOPT_POST, true);
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
    $resp = curl_exec ( $ch );
    curl_close ( $ch );
    return $resp;
	}
	

	function object2array($object) {
		$array = array();
		if (is_object($object)) {
			foreach ($object as $key => $value) {
				if(is_object($value)){
					$array[$key] = $this->object2array($value);
				}else{
					$array[$key] = $value;
				}
			}
		}else {
			$array = $object;
		}
		return $array;
	}
	
}
?>